package com.liuyi.netty.im.lychat.modular.service;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.liuyi.netty.im.lychat.LychatConst;
import com.liuyi.netty.im.lychat.modular.caches.UserCache;
import com.liuyi.netty.im.lychat.modular.entity.User;
import com.liuyi.netty.im.lychat.modular.mapper.UserMapper;
import com.liuyi.rapid.develop.mybatis.plus.base.IBaseService;
import com.liuyi.rapid.develop.tool.unusual.BizException;

/**
 * <p>
 * 用户表 服务类
 * </p>
 *
 * @author mybatis-plus
 * @since 2021-12-29
 */
public interface IUserService extends IBaseService<User> {

    @Override
    default Class<User> getEntityClass() {
        return User.class;
    }

    @Override
    @SuppressWarnings("unchecked")
    default UserMapper getMapper() {
        return (UserMapper) getBaseMapper();
    }

    UserCache cache();

    default User createUser(String userId, String password) {
        return createUser(userId, null, password);
    }

    default User createUser(String userId, String userNick, String password) {
        User user = new User();
        if (this.count(User.USER_ID, userId) > 0) {
            throw new BizException("抱歉，用户名已存在，请更换");
        }
        user.setUserId(userId).setSalt(RandomUtil.randomString(32))
                .setPassword(LychatConst.md5UsserPassword(password, user.getSalt()))
                .setNick(StrUtil.isEmpty(userNick) ? RandomUtil.randomNumbers(3) : userNick)
                .setHead(LychatConst.DEFAULT_USER_HEAD);
        this.save(user);
        return user;
    }
}
